# Run Analysis for Robustness Checks
# Alexander F. Gazmararian
# agazmararian@gmail.com

library(here)

# Configuration for robustness comparisons
ROBUSTNESS_CHECKS <- c(
  "primary" = NULL,
  "codebook_robustness" = "codebook_robustness"
)

# Run analysis for each robustness check
message("=== RUNNING ANALYSIS FOR MULTIPLE ANNOTATION VERSIONS ===")

for (check_name in names(ROBUSTNESS_CHECKS)) {
  message(sprintf("\n--- Processing %s analysis ---", check_name))
  
  # Set the global variable for the analysis script
  ROBUSTNESS_CHECK <- ROBUSTNESS_CHECKS[[check_name]]
  
  # Check if input file exists
  if (!is.null(ROBUSTNESS_CHECK)) {
    input_file <- here("data", "output", sprintf("statements_analysis_%s.csv", ROBUSTNESS_CHECK))
  } else {
    input_file <- here("data", "output", "statements_analysis.csv")
  }
  
  if (!file.exists(input_file)) {
    message(sprintf("Skipping %s: Input file not found at %s", check_name, input_file))
    next
  }
  
  # Run analysis by sourcing the analyze.R script
  tryCatch({
    # Set the global variable for this iteration
    assign("ROBUSTNESS_CHECK", ROBUSTNESS_CHECK, envir = .GlobalEnv)
    
    # Source the analysis script
    source(here("analysis", "statements", "analyze.R"))
    
    message(sprintf("Successfully completed %s analysis", check_name))
    
    # Clean up: remove the variable so it doesn't interfere with next iteration
    if (exists("ROBUSTNESS_CHECK", envir = .GlobalEnv)) {
      rm("ROBUSTNESS_CHECK", envir = .GlobalEnv)
    }
    
  }, error = function(e) {
    message(sprintf("Error in %s analysis: %s", check_name, e$message))
    print(e)  # Print full error for debugging
    
    # Clean up on error too
    if (exists("ROBUSTNESS_CHECK", envir = .GlobalEnv)) {
      rm("ROBUSTNESS_CHECK", envir = .GlobalEnv)
    }
  })
}

message("\n=== ANALYSIS ROBUSTNESS CHECK COMPLETE ===")
message("Check output directories for:")
message("- Figures: output/pnas/figures/")
message("- Tables: output/pnas/tables/")
message("Files with suffixes indicate robustness check results")
